package com.futvan.z.system.zfile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;

import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.core.SuperAction;
import com.futvan.z.framework.core.z;
import com.futvan.z.framework.util.DateUtil;
import com.futvan.z.framework.util.ImgUtil;
import com.futvan.z.framework.util.JsonUtil;
import com.futvan.z.framework.util.StringUtil;
import com.futvan.z.framework.util.SystemUtil;
import com.futvan.z.system.zfile.ZfileService;
import com.futvan.z.system.zform.z_form_table;
@Controller
public class ZfileAction extends SuperAction{
	@Autowired
	private ZfileService zfileService;
	private List<File> filelist;

	/**
	 * 获取所有本地文件
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/all_file_list")
	public ModelAndView all_file_list() {
		ModelAndView mv = new ModelAndView("system/zfile/all_file_list");
		mv.addObject("filelist", GetFileList());
		return mv;
	}
	
	/**
	 * 删除文件
	 * @param zid
	 * @return
	 */
	@RequestMapping(value="/deleteLocalFile",method=RequestMethod.GET)
	public @ResponseBody Result deleteLocalFile(String zid){
		Result result = new Result();
		if(z.isNotNull(zid)) { 
			String zfilepath = StringUtil.jie_old(zid).replace("☆", "\\");
			File file = new File(zfilepath);
			if(file.exists() && file.isFile()) {
				boolean isDelete = file.delete();
				if(isDelete) {
					result.setCode(Code.SUCCESS);
					result.setMsg("成功删除文件");
				}else {
					result.setCode(Code.ERROR);
					result.setMsg("删除文件不成功");
				}
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("未找到文件");
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("zid is null");
		}
		return result;
	}
	
	private List<z_file> GetFileList() {
		List<z_file> fl = new ArrayList<z_file>();
		File files_path = new File(request.getServletContext().getRealPath("/")+"files");
		filelist = new ArrayList<File>();
		//遍历文件目录，获取所有文件
		getDirAllFileList(files_path);
		filelist.sort(new Comparator<File>() {
			public int compare(File o1, File o2) {
				if(o1.lastModified()==o2.lastModified()) {
					return 0;
				}else if(o1.lastModified()>o2.lastModified()) {
					return -1;
				}else {
					return 1;
				}
			}
		});

		for (File f : filelist) {
			z_file zf = new z_file();
			zf.setZid(StringUtil.jia_old(f.getPath().replace("\\", "☆")));
			zf.setName(f.getName());
			//zf.setType(type);
			String size = "";
			if(f.length()<=1048576) {
				size = String.valueOf(f.length()/1024)+"K";
			}else if(f.length()>1048576 && f.length()<=1073741824) {
				size = String.valueOf(f.length()/1024/1024)+"M";
			}else if(f.length()>1073741824){
				size = String.valueOf(f.length()/1024/1024/1024)+"G";
			}
			zf.setSize(size);
			zf.setCreate_time(DateUtil.FormatDate(new Date(f.lastModified()), "yyyy-MM-dd HH:mm:ss"));
			String serverip = "";
			if("true".equals(z.sp.get("serverip"))) {
				serverip = "https://"+z.sp.get("serverip");
			}else {
				serverip = "http://"+z.sp.get("serverip");
			}
			zf.setFilepath(serverip+"/files"+f.getPath().replace(files_path.getPath(), "").replace("\\", "/"));
			fl.add(zf);
		}
		return fl;
	}
	
	private void getDirAllFileList(File dir) {
		if(dir.exists() && dir.isDirectory() && z.isNotNull(filelist)) {
			File[] files = dir.listFiles();
			for (File df : files) {
				if (df.isDirectory()) {
					getDirAllFileList(df);
				} else {
					filelist.add(df);
				}
			}
		}

	}
	
	/**
	 * 
	 * @return
	 * @throws Exception
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value="/upload")
	public @ResponseBody Result upload(String filepath,HttpServletRequest request){
		Result result = new Result();
		String fileReturnPath = "";
		List<String> uploadFileList = new ArrayList<String>();
		try {
			//将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
			CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
			//检查form中是否有enctype="multipart/form-data"
			if(multipartResolver.isMultipart(request)){
				//将request变成多部分request
				MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
				//获取multiRequest 中所有的文件名
				Iterator iter=multiRequest.getFileNames();
				while(iter.hasNext()){
					//一次遍历所有文件
					MultipartFile file=multiRequest.getFile(iter.next().toString());
					if(file!=null){
						//创建保存路径
						String fileSavePath = CreateFileSavePath(filepath);
						
						//保存文件
						save(file,fileSavePath+"/"+file.getOriginalFilename());
						
						//创建返回URL
						fileReturnPath = z.sp.get("fileserverurl")+"/files/"+filepath+"/"+file.getOriginalFilename();
						uploadFileList.add(fileReturnPath);
						
						//如果是图片，返回压缩图片路径
						if(ImgUtil.isImg(file.getOriginalFilename())) {
							String z1_fileReturnPath = z.sp.get("fileserverurl")+"/files/"+filepath+"/"+ file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")) +"_z1." + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1); 
							uploadFileList.add(z1_fileReturnPath);
							
							String z5_fileReturnPath = z.sp.get("fileserverurl")+"/files/"+filepath+"/"+ file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")) +"_z5." + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1); 
							uploadFileList.add(z5_fileReturnPath);
						}
						
						
						//保存文件名到数据库
						zfileService.save(fileReturnPath,filepath,z.sp.get("fileserverurl"),file);
					}
				}
			}
			result.setCode(Code.SUCCESS);
			result.setMsg(JsonUtil.listToJson(uploadFileList));
			result.setData(fileReturnPath);
		} catch (Exception e) {
			result.setCode(Code.ERROR);
			result.setMsg("file upload error："+e.getMessage());
			result.setData(e.getMessage());
		} 
		return result;
	}

	private String CreateFileSavePath(String filepath) throws Exception{
		String fileSavePath = "";
		String project_path = System.getProperty("web.root");
		if(!"".equals(project_path) && project_path!=null) {
			fileSavePath = project_path;
			//判读路径是否为空
			if(!"".equals(filepath) && filepath!=null) {
				fileSavePath = fileSavePath+"/files/"+filepath;
			}

			// 判断文件目录是否存在如果不存在怎么创建
			File dir = new File(fileSavePath);
			if (!dir.exists() && !dir.isDirectory()) {
				//创建多级目录
				dir.mkdirs();
			}
		}else {
			throw new Exception("文件服务器系统错误:创建文件保存路径出错。请稍后上传。");
		}
		return fileSavePath;
	}

	/**
	 * 保存文件
	 * @throws Exception
	 */
	private void save(MultipartFile file,String fileSavePath) throws Exception{
		file.transferTo(new File(fileSavePath));

		//同时生成压缩文件
		ImgUtil.ImgZip(fileSavePath);
	}
}
